package com.atguigu.flow.utils;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.flow.config.TaxCloudConfig;
import com.atguigu.flow.entity.SysAttachment;
import com.atguigu.flow.mapper.SqlMapper;
import com.atguigu.flow.mapper.SysAttachmentMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Component
public
class AttachmentSave {
    @Autowired
    SqlMapper sqlMapper;
    @Autowired
    private SysAttachmentMapper sysAttachmentMapper;
    @Autowired
    TaxCloudConfig taxCloudConfig;

    public
    JSONObject attachmenttobase64(String parentid, String recordid, String filename){
        QueryWrapper<SysAttachment> wrapper = new QueryWrapper<>();
        wrapper.eq("recordid", recordid)
                .eq("parentid", parentid);
        SysAttachment sysAttachment = new SysAttachment();
        String str="无记录";
        JSONObject json=new JSONObject();
        int count=sysAttachmentMapper.selectCount(wrapper);
        if (count>0) {
            sysAttachment = sysAttachmentMapper.selectOne(wrapper);
            String achmentpath = taxCloudConfig.getAttachmentpath();

            File dest1 = new File(achmentpath + sysAttachment.getStoredPath().replace("\\", "/")
                    + sysAttachment.getRecordID() + ".iAttachment");
            if (dest1.exists()) {
                System.out.println(dest1.getPath());
                 str=Base64Util.encryptToBase64(dest1.getPath());

            }
            else str="";
            json.put("filename",sysAttachment.getName());
            json.put("Base64",str);

        }else
        {
            json.put("filename",filename);
            json.put("Base64","");
        }

        if (str.contains("无记录"))
            json.put("error",str);
        return json;
    }
    public String attachmentsavedb(byte[] datas,String docbillId, String parentid,String modulename,String tablename) throws Exception{
//        String docbillId="";
//        docbillId="414727";
        String str="";
//        byte[] datas= Zxb_receivedata.doEdiDocumentDownload(docbillId);
//        System.out.println(datas);
        if (datas != null) {

//            String parentid="64444A69-984E-4BCD-8F06-02ACF0DAAE6B";
//            String parentid = "976E1341-48ED-4113-9E06-A93BE3313B5E";
            QueryWrapper<SysAttachment> wrapper = new QueryWrapper<>();
            wrapper.eq("name", docbillId+".pdf").eq("module", modulename)
                    .eq("parentid", parentid);
            SysAttachment sysAttachment = new SysAttachment();
            Integer count = sysAttachmentMapper.selectCount(wrapper);

            if (count > 0) {
                SysAttachment sysAttachment1 = sysAttachmentMapper.selectOne(wrapper);
                String achmentpath = "D:\\Program Files (x86)\\Intersky\\Smarterp\\Middleware Server\\Data\\本地\\Attachment\\";

                File dest1 = new File(achmentpath + sysAttachment1.getStoredPath().replace("\\", "/")
                        + sysAttachment1.getRecordID() + ".iAttachment");
                if (dest1.exists()) {
                    str="数据已下载，无需重复下载";
                    return str;}
                    else
                    //dest1.delete();

                sysAttachmentMapper.delete(wrapper);
            }


            String datePath = DateUtil.fileformatDate(new Date());
            String uuid = UUID.randomUUID().toString().toUpperCase();
            String filepath = uuid + ".iAttachment";
            filepath = "D:\\Program Files (x86)\\Intersky\\Smarterp\\Middleware Server\\Data\\本地\\Attachment\\" + datePath + filepath;
            ;
            File dest = new File(filepath);
            //检测是否存在该目录
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }

            Zxb_receivedata.convertByteArrayToFile(filepath, datas);
            sysAttachment.setDate(new Date());
            sysAttachment.setParentID(parentid);
            sysAttachment.setModule(modulename);
            sysAttachment.setName(docbillId+".pdf");
            sysAttachment.setSize((int) dest.length());
            sysAttachment.setRecordID(uuid);
            sysAttachment.setStoredPath(datePath.replace("/", "\\"));
            count = sysAttachmentMapper.insert(sysAttachment);
            if (count > 0) {
                str="新增"+modulename + docbillId+ "成功";

                Map<String, Object> params = new HashMap<>();
                params.clear();
                params.put("sql", "select COUNT(*)xj  from "+tablename+" where RecordID=#{recordid} and HaveAttachment=1");
                params.put("recordid", parentid);

                count = sqlMapper.sqlcount(params);
                if (count == 0) {
                    params.clear();
                    params.put("sql", "update "+tablename+" set  HaveAttachment=1 where RecordID=#{recordid}  ");
                    params.put("recordid", parentid);
                    count = sqlMapper.sqlcount(params);

                }

            }

        }
        else str="下载的数据为空";
      return str;
    }
}
